package com.ly.honor.config;

import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author 李某人
 * @Date 2023/3/20 21:59
 * @Version 1.0
 */
@Configuration
public class RedisConfig {

//    @Bean //redisTemplate注入到Spring容器
//    public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory factory){
//        RedisTemplate<String,String> redisTemplate=new RedisTemplate<>();
//        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
//        redisTemplate.setConnectionFactory(factory);
//        //key序列化
//        redisTemplate.setKeySerializer(redisSerializer);
//        //value序列化
//        redisTemplate.setValueSerializer(redisSerializer);
//        //value hashmap序列化
//        redisTemplate.setHashKeySerializer(redisSerializer);
//        //key hashmap序列化
//        redisTemplate.setHashValueSerializer(redisSerializer);
//        return redisTemplate;
//    }

    @Bean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();

        // 实例化序列化器 FastJsonRedisSerializer
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);

        // value 的序列化采用 FastJsonRedisSerializer [包括 String 类型和 Hash 类型]
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setHashValueSerializer(fastJsonRedisSerializer);

        // 全局开启 AutoType，这里方便开发，使用全局的方式，即允许所有包的序列化和反序列化，官方不推荐使用
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        // 建议使用这种方式，小范围指定白名单，即指定小范围包的序列化和反序列化
        // ParserConfig.getGlobalInstance().addAccept("club.wadreamer.demo.entity");

        // key 的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        template.setConnectionFactory(redisConnectionFactory);

        return template;
    }


}
